package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 检查用户是否登陆了
 */
@Slf4j
@WebFilter(filterName = "LoginCheckFilter", urlPatterns = "/*")//声明这个类为过滤器,指定过滤名字的属性,指定一组过滤器的url匹配模式
public class LoginCheckFilter implements Filter {
    //路径匹配器，支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //对请求,响应进行强转
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //获得本次请求的url
        String requestURI = request.getRequestURI();
        log.info("拦截到的请求{}", requestURI);

        //定义不需要处理的请求路径[静态资源,登陆,退出]
        String[] url = new String[]{
                "/employee/login",  //登陆请求
                "/employee/logout",    //退出请求
                "/backend/**",         //静态资源
                "/front/**",             //静态资源
                "/common/**",             //上传下载图片
                "/user/sendMsg",             //上传下载图片
                "/user/login"             //上传下载图片

        };

        //判断本次请求是否需要处理
        boolean method = method(url, requestURI);

        //如果不需要处理,放行
        if (method) {
            log.info("拦截到请求{}", requestURI);
            //放行
            filterChain.doFilter(request, response);
            //程序不需要往后进行了  此处的return非常关键,如果没有此时的return ,代码会有bug
            return;
        }
        //判断登陆状态,登陆放行,否则拦截
        if (request.getSession().getAttribute("employee") != null) {
            log.info("用虎已登陆id{}", request.getSession().getAttribute("employee"));
            //把当前登陆用户id设置到当前线程中
            BaseContext.setCurrentId((Long) request.getSession().getAttribute("employee"));
            filterChain.doFilter(request, response);
            return;
        }
        //判断前端登陆
        if (request.getSession().getAttribute("user") != null) {
            log.info("用户已经登录,用户的id为:", request.getSession().getAttribute("user"));

            //获取当前登录用户的id
            Long empId = (Long) request.getSession().getAttribute("user");
            //向当前的线程对象绑定了id
            BaseContext.setCurrentId(empId);
            //放行
            filterChain.doFilter(request, response);
            //程序不需要往后进行了  此处的return非常关键,如果没有此时的return ,代码会有bug
            return;
        }

        log.info("用户未登录", requestURI);
        //设置本次响应内容类型和编码
        response.setContentType("application/json;charset=utf-8");
        //构建R对象,携带这NOTLOGING字符串
        R r = R.error("NOTLOGIN");
        String jsonStr = JSON.toJSONString(r); //将r转换为json字符串
        //如果没有登陆,给前端页面发送json对象
        response.getWriter().write(jsonStr);
    }

    /**
     * 路径匹配查询,检查本次请求是否放行
     *
     * @param url
     * @param requestURI
     * @return
     */
    public boolean method(String[] url, String requestURI) {
        //看本次请求的路径requestURI是否和urls中的路径匹配
        for (String s : url) {
            boolean match = PATH_MATCHER.match(s, requestURI);
            //匹配返回true,本次请求不需要做处理，直接放行
            if (match) {
                return true;
            }
        }
        //不匹配返回false,本次请求需要做处理，拦截下来
        return false;
    }

}
